import Router from 'koa-router';
import { pool } from '../../config/database';
import { authMiddleware } from '../../middleware/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { ApiResponse, JwtPayload } from '../../types';
import { chatManager } from '../../websocket/server';
import { formatDisplayTime } from '../../utils/time';

const router = new Router({ prefix: '/api/chat' });

// 处理查询结果中的时间字段
function processTimeFields(data: any): any {
  if (!data) return data;
  
  if (Array.isArray(data)) {
    return data.map(item => processTimeFields(item));
  }
  
  if (typeof data === 'object') {
    const processed = { ...data };
    
    // 处理时间字段
    const timeFields = ['created_at', 'updated_at', 'last_message_time', 'started_at', 'ended_at'];
    for (const field of timeFields) {
      if (processed[field]) {
        processed[field] = formatDisplayTime(processed[field]);
      }
    }
    
    return processed;
  }
  
  return data;
}

// 获取聊天历史
router.get('/history', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { page = 1, limit = 50, user_id } = ctx.query;
    const offset = (Number(page) - 1) * Number(limit);

    let query = `
      SELECT cm.*, u.nickname, u.avatar, u.id as sender_id
      FROM chat_messages cm 
      LEFT JOIN users u ON cm.user_id = u.id 
      WHERE 1=1
    `;
    let queryParams: any[] = [];

    // 根据用户角色过滤消息
    if (user.role === 'admin') {
      // 管理员可以看到所有消息，如果指定了user_id，则只看该用户的消息
      if (user_id) {
        query += ' AND cm.user_id = ?';
        queryParams.push(Number(user_id));
      }
    } else {
      // 普通用户只能看到自己的消息
      query += ' AND cm.user_id = ?';
      queryParams.push(user.id);
    }

    query += ' ORDER BY cm.created_at DESC LIMIT ? OFFSET ?';
    queryParams.push(Number(limit), offset);

    const [messages] = await pool.query(query, queryParams) as [RowDataPacket[], any];

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM chat_messages WHERE 1=1';
    let countParams: any[] = [];
    
    // 根据用户角色过滤
    if (user.role === 'admin') {
      if (user_id) {
        countQuery += ' AND user_id = ?';
        countParams.push(Number(user_id));
      }
    } else {
      countQuery += ' AND user_id = ?';
      countParams.push(user.id);
    }

    const [countResult] = await pool.query(countQuery, countParams) as [RowDataPacket[], any];
    const total = (countResult && countResult[0]) ? countResult[0].total : 0;

    ctx.body = {
      success: true,
      data: processTimeFields(messages.reverse()), // 按时间正序返回
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(total / Number(limit))
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取聊天历史失败：' + error.message
    } as ApiResponse;
  }
});

// 获取聊天会话列表 - 简化版，不依赖chat_sessions表
router.get('/sessions', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    if (user.role !== 'admin' && user.role !== 'customer_service') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限访问此接口'
      } as ApiResponse;
      return;
    }

    // 直接使用user-sessions接口的逻辑
    const { page = 1, limit = 20 } = ctx.query;
    
    const offset = (Number(page) - 1) * Number(limit);

    // 获取有消息的用户列表，按最后消息时间排序
    const query = `
      SELECT DISTINCT
        u.id as user_id,
        u.nickname,
        u.avatar,
        u.role,
        (SELECT COUNT(*) FROM chat_messages cm 
         WHERE cm.user_id = u.id AND cm.is_read = 0 AND cm.message_type = 'user') as unread_count,
        (SELECT cm.message FROM chat_messages cm 
         WHERE cm.user_id = u.id 
         ORDER BY cm.created_at DESC LIMIT 1) as last_message,
        (SELECT cm.created_at FROM chat_messages cm 
         WHERE cm.user_id = u.id 
         ORDER BY cm.created_at DESC LIMIT 1) as last_message_time,
        (SELECT cm.message_type FROM chat_messages cm 
         WHERE cm.user_id = u.id 
         ORDER BY cm.created_at DESC LIMIT 1) as last_message_type
      FROM users u
      WHERE u.id IN (SELECT DISTINCT user_id FROM chat_messages)
        AND u.role = 'user'
      ORDER BY last_message_time DESC
      LIMIT ? OFFSET ?
    `;

    const [sessions] = await pool.query(query, [Number(limit), offset]) as [RowDataPacket[], any];

    // 获取总数
    const [countResult] = await pool.query(
      `SELECT COUNT(DISTINCT u.id) as total 
       FROM users u 
       WHERE u.id IN (SELECT DISTINCT user_id FROM chat_messages) 
         AND u.role = 'user'`
    ) as [RowDataPacket[], any];
    const total = (countResult && countResult[0]) ? countResult[0].total : 0;

    ctx.body = {
      success: true,
      data: processTimeFields(sessions),
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(total / Number(limit))
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取会话列表失败：' + error.message
    } as ApiResponse;
  }
});


// 结束聊天会话
router.post('/sessions/:sessionId/close', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { sessionId } = ctx.params;
    const { rating, feedback } = ctx.request.body as any;

    // 检查会话是否存在且用户有权限操作
    const sessions = await pool.query(
      'SELECT * FROM chat_sessions WHERE id = ?',
      [sessionId]
    ) as [RowDataPacket[], any];

    if (sessions[0].length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '会话不存在'
      } as ApiResponse;
      return;
    }

    const session = sessions[0][0];

    // 检查权限
    if (session.user_id !== user.id && user.role !== 'admin' && user.role !== 'customer_service') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限操作此会话'
      } as ApiResponse;
      return;
    }

    // 更新会话状态 - 使用NOW()函数
    await pool.query(
      `UPDATE chat_sessions 
       SET status = 'closed', ended_at = NOW(), rating = ?, feedback = ?, updated_at = NOW() 
       WHERE id = ?`,
      [rating || null, feedback || null, sessionId]
    );

    ctx.body = {
      success: true,
      message: '会话已结束'
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '结束会话失败：' + error.message
    } as ApiResponse;
  }
});

// 获取在线客服状态
router.get('/service/status', async (ctx) => {
  try {
    const stats = chatManager.getStats();
    
    ctx.body = {
      success: true,
      data: {
        adminOnline: stats.adminOnline,
        adminCount: stats.adminCount,
        totalUsers: stats.totalUsers,
        normalUserCount: stats.normalUserCount
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取聊天状态失败：' + error.message
    } as ApiResponse;
  }
});

// 获取用户在线状态（管理员专用）
router.get('/users/online-status', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    if (user.role !== 'admin' && user.role !== 'customer_service') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限访问此接口'
      } as ApiResponse;
      return;
    }

    const { userIds } = ctx.query; // 可选：只查询特定用户的状态

    let targetUserIds: number[] = [];
    
    if (userIds) {
      // 解析用户ID列表
      try {
        targetUserIds = Array.isArray(userIds) 
          ? userIds.map(id => Number(id)) 
          : [Number(userIds)];
      } catch (error) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '用户ID格式错误'
        } as ApiResponse;
        return;
      }
    } else {
      // 获取所有有聊天记录的用户ID
      const [userList] = await pool.query(
        `SELECT DISTINCT user_id FROM chat_messages 
         WHERE user_id IN (SELECT id FROM users WHERE role = 'user')`
      ) as [RowDataPacket[], any];
      targetUserIds = userList.map(row => row.user_id);
    }

    // 检查每个用户的在线状态
    const onlineStatus = targetUserIds.map(userId => ({
      userId,
      isOnline: chatManager.isUserOnline(userId)
    }));

    ctx.body = {
      success: true,
      data: {
        onlineStatus,
        stats: chatManager.getStats()
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取用户在线状态失败：' + error.message
    } as ApiResponse;
  }
});

// 管理员向特定用户发送消息
router.post('/send-message', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    if (user.role !== 'admin' && user.role !== 'customer_service') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限发送消息'
      } as ApiResponse;
      return;
    }

    const { message, target_user_id } = ctx.request.body as any;

    if (!message || !message.trim()) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '消息内容不能为空'
      } as ApiResponse;
      return;
    }

    if (!target_user_id) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '必须指定目标用户'
      } as ApiResponse;
      return;
    }

    // 检查目标用户是否存在
    const [targetUser] = await pool.query(
      'SELECT id, nickname, username, email FROM users WHERE id = ? AND role = "user"',
      [target_user_id]
    ) as [RowDataPacket[], any];

    if (targetUser.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '目标用户不存在'
      } as ApiResponse;
      return;
    }

    // 获取管理员信息
    const [adminInfo] = await pool.query(
      'SELECT id, nickname, username, email, avatar FROM users WHERE id = ?',
      [user.id]
    ) as [RowDataPacket[], any];

    const adminDetails = adminInfo[0];
    const adminDisplayName = adminDetails.nickname || adminDetails.username || adminDetails.email;

    // 保存消息到数据库 - 使用实际发送者（管理员）的ID，并设置room_id关联对话
    const roomId = `user_${target_user_id}`;
    await pool.query(
      'INSERT INTO chat_messages (user_id, message, message_type, room_id, created_at) VALUES (?, ?, ?, ?, NOW())',
      [user.id, message.trim(), 'customer_service', roomId]
    );

    // 通过WebSocket发送消息
    const chatMessage = {
      type: 'message' as const,
      data: {
        message: message.trim(),
        userId: user.id, // 发送者ID（管理员）
        userName: adminDisplayName,
        nickname: adminDetails.nickname,
        avatar: adminDetails.avatar,
        isAdmin: true,
        targetUserId: target_user_id
      },
      timestamp: Date.now(),
      targetUserId: target_user_id
    };

    // 发送给目标用户
    const userOnline = chatManager.isUserOnline(target_user_id);
    if (userOnline) {
      chatManager.sendToUserId(target_user_id, chatMessage);
    }

    // 同步给其他管理员
    chatManager.broadcastToAdmins(chatMessage);

    ctx.body = {
      success: true,
      message: userOnline ? '消息发送成功' : '消息已保存，用户当前离线',
      data: {
        userOnline,
        targetUserName: targetUser[0].nickname || targetUser[0].username || targetUser[0].email
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '发送消息失败：' + error.message
    } as ApiResponse;
  }
});

// 发送系统消息（仅管理员）
router.post('/system/message', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    if (user.role !== 'admin') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限发送系统消息'
      } as ApiResponse;
      return;
    }

    const { message, target_user_id } = ctx.request.body as any;

    if (!message) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '消息内容不能为空'
      } as ApiResponse;
      return;
    }

    // 保存系统消息到数据库 - 使用NOW()函数
    if (target_user_id) {
      const roomId = `user_${target_user_id}`;
      await pool.query(
        'INSERT INTO chat_messages (user_id, message, message_type, room_id, created_at) VALUES (?, ?, ?, ?, NOW())',
        [user.id, message, 'customer_service', roomId]
      );
    }

    // TODO: 通过WebSocket发送系统消息（需要扩展chatManager功能）

    ctx.body = {
      success: true,
      message: '系统消息发送成功'
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '发送系统消息失败：' + error.message
    } as ApiResponse;
  }
});

// 客服管理API（仅管理员）
router.get('/admin/stats', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    if (user.role !== 'admin') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限访问管理数据'
      } as ApiResponse;
      return;
    }

    // 获取聊天统计数据
    const todayMessages = await pool.query(
      'SELECT COUNT(*) as count FROM chat_messages WHERE DATE(created_at) = CURDATE()',
      []
    ) as [RowDataPacket[], any];

    const totalSessions = await pool.query(
      'SELECT COUNT(*) as total, status, COUNT(CASE WHEN DATE(started_at) = CURDATE() THEN 1 END) as today FROM chat_sessions GROUP BY status',
      []
    ) as [RowDataPacket[], any];

    const avgRating = await pool.query(
      'SELECT AVG(rating) as avg_rating, COUNT(rating) as rated_sessions FROM chat_sessions WHERE rating IS NOT NULL',
      []
    ) as [RowDataPacket[], any];

    const realTimeStats = chatManager.getStats();

    ctx.body = {
      success: true,
      data: {
        todayMessages: (todayMessages && todayMessages[0] && todayMessages[0][0]) ? todayMessages[0][0].count : 0,
        sessions: totalSessions[0],
        avgRating: (avgRating && avgRating[0] && avgRating[0][0]) ? (avgRating[0][0].avg_rating || 0) : 0,
        ratedSessions: (avgRating && avgRating[0] && avgRating[0][0]) ? (avgRating[0][0].rated_sessions || 0) : 0,
        realTime: {
          totalUsers: realTimeStats.totalUsers,
          adminCount: realTimeStats.adminCount,
          normalUserCount: realTimeStats.normalUserCount,
          adminOnline: realTimeStats.adminOnline,
          totalConnections: realTimeStats.totalConnections,
          uniqueUsers: realTimeStats.uniqueUsers
        }
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取统计数据失败：' + error.message
    } as ApiResponse;
  }
});

// 获取详细的连接状态（调试接口，仅管理员）
router.get('/admin/connections', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    if (user.role !== 'admin') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限访问调试数据'
      } as ApiResponse;
      return;
    }

    const detailedStats = chatManager.getDetailedStats();

    ctx.body = {
      success: true,
      data: processTimeFields(detailedStats),
      message: '连接状态详情'
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取连接状态失败：' + error.message
    } as ApiResponse;
  }
});

// 获取未读消息数量
router.get('/unread-count', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    const result = await pool.query(
      'SELECT COUNT(*) as count FROM chat_messages WHERE user_id != ? AND is_read = 0',
      [user.id]
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: {
        unreadCount: (result && result[0] && result[0][0]) ? result[0][0].count : 0
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取未读消息数量失败：' + error.message
    } as ApiResponse;
  }
});

// 标记消息为已读
router.post('/mark-read', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { messageIds } = ctx.request.body as any;

    let query = 'UPDATE chat_messages SET is_read = 1, updated_at = NOW() WHERE user_id != ? AND is_read = 0';
    let params = [user.id];
    
    // 如果指定了特定消息ID，只标记这些消息
    if (messageIds && Array.isArray(messageIds) && messageIds.length > 0) {
      query += ` AND id IN (${messageIds.map(() => '?').join(',')})`;
      params.push(...messageIds);
    }
    
    await pool.query(query, params);

    // 获取最新的未读数量
    const result = await pool.query(
      'SELECT COUNT(*) as count FROM chat_messages WHERE user_id != ? AND is_read = 0',
      [user.id]
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: {
        unreadCount: (result && result[0] && result[0][0]) ? result[0][0].count : 0
      },
      message: '消息已标记为已读'
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '标记消息已读失败：' + error.message
    } as ApiResponse;
  }
});

// 获取用户的简化聊天会话列表（管理员专用）
router.get('/user-sessions', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    
    if (user.role !== 'admin' && user.role !== 'customer_service') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限访问此接口'
      } as ApiResponse;
      return;
    }

    const { page = 1, limit = 20 } = ctx.query;
    const offset = (Number(page) - 1) * Number(limit);

    // 获取有消息的用户列表，按最后消息时间排序
    const query = `
      SELECT DISTINCT
        u.id as user_id,
        u.nickname,
        u.username,
        u.avatar,
        u.role,
        (SELECT COUNT(*) FROM chat_messages cm 
         WHERE cm.user_id = u.id AND cm.is_read = 0 AND cm.message_type = 'user') as unread_count,
        (SELECT cm.message FROM chat_messages cm 
         WHERE cm.user_id = u.id 
         ORDER BY cm.created_at DESC LIMIT 1) as last_message,
        (SELECT cm.created_at FROM chat_messages cm 
         WHERE cm.user_id = u.id 
         ORDER BY cm.created_at DESC LIMIT 1) as last_message_time,
        (SELECT cm.message_type FROM chat_messages cm 
         WHERE cm.user_id = u.id 
         ORDER BY cm.created_at DESC LIMIT 1) as last_message_type
      FROM users u
      WHERE u.id IN (SELECT DISTINCT user_id FROM chat_messages)
        AND u.role = 'user'
      ORDER BY last_message_time DESC
      LIMIT ? OFFSET ?
    `;

    const [userSessions] = await pool.query(query, [Number(limit), offset]) as [RowDataPacket[], any];

    // 添加在线状态信息
    const userSessionsWithOnlineStatus = userSessions.map(session => ({
      ...session,
      isOnline: chatManager.isUserOnline(session.user_id),
      displayName: session.nickname || session.username
    }));

    // 获取总数
    const [countResult] = await pool.query(
      `SELECT COUNT(DISTINCT u.id) as total 
       FROM users u 
       WHERE u.id IN (SELECT DISTINCT user_id FROM chat_messages) 
         AND u.role = 'user'`,
      []
    ) as [RowDataPacket[], any];
    const total = (countResult && countResult[0]) ? countResult[0].total : 0;

    ctx.body = {
      success: true,
      data: processTimeFields(userSessionsWithOnlineStatus),
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(total / Number(limit))
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取用户会话列表失败：' + error.message
    } as ApiResponse;
  }
});

// 获取与特定用户的聊天记录（管理员专用）
router.get('/user-messages/:userId', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { userId } = ctx.params;
    
    if (user.role !== 'admin' && user.role !== 'customer_service') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限访问此接口'
      } as ApiResponse;
      return;
    }

    const { page = 1, limit = 50 } = ctx.query;
    const offset = (Number(page) - 1) * Number(limit);

    // 获取该用户对话中的所有消息（用户发送的+管理员回复的）
    const roomId = `user_${userId}`;
    const query = `
      SELECT cm.*, 
             u.nickname, 
             u.avatar,
             u.role,
             CASE 
               WHEN cm.message_type = 'customer_service' THEN 1 
               ELSE 0 
             END as is_admin_message,
             CASE 
               WHEN cm.message_type = 'customer_service' THEN cm.user_id
               ELSE NULL 
             END as actual_sender_id
      FROM chat_messages cm 
      LEFT JOIN users u ON (
        CASE 
          WHEN cm.message_type = 'customer_service' THEN cm.user_id
          ELSE cm.user_id
        END = u.id
      )
      WHERE (cm.user_id = ? AND cm.message_type = 'user') 
         OR (cm.room_id = ? AND cm.message_type = 'customer_service')
         OR (cm.user_id = ? AND cm.message_type = 'customer_service' AND cm.room_id IS NULL)
      ORDER BY cm.created_at DESC 
      LIMIT ? OFFSET ?
    `;

    const [messages] = await pool.query(query, [userId, roomId, userId, Number(limit), offset]) as [RowDataPacket[], any];

    // 获取总数
    const [countResult] = await pool.query(
      `SELECT COUNT(*) as total FROM chat_messages 
       WHERE (user_id = ? AND message_type = 'user') 
          OR (room_id = ? AND message_type = 'customer_service')
          OR (user_id = ? AND message_type = 'customer_service' AND room_id IS NULL)`,
      [userId, roomId, userId]
    ) as [RowDataPacket[], any];
    const total = (countResult && countResult[0] && countResult[0][0]) ? countResult[0][0].total : 0;

    // 标记该用户的消息为已读
    await pool.query(
      'UPDATE chat_messages SET is_read = 1 WHERE user_id = ? AND message_type = "user" AND is_read = 0',
      [userId]
    );

    ctx.body = {
      success: true,
      data: processTimeFields(messages.reverse()), // 按时间正序返回
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(total / Number(limit))
      }
    } as ApiResponse;

  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取聊天记录失败：' + error.message
    } as ApiResponse;
  }
});

export default router; 